﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

using NHibernate;
using NHibernate.Linq;

namespace Grebok.Persistence.Nhibernate
{
    using Grebok.Domain;

    public class Repository<T> : IRepository<T>
    {
        private readonly ISessionFactory sessionFactory;

        public Repository(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }

        #region Implementation of IQueryable

        public Expression Expression
        {
            get { return sessionFactory.GetCurrentSession().Linq<T>().Expression; }
        }

        public Type ElementType
        {
            get { return sessionFactory.GetCurrentSession().Linq<T>().ElementType; }
        }

        public IQueryProvider Provider
        {
            get { return sessionFactory.GetCurrentSession().Linq<T>().Provider; }
        }

        #endregion

        #region Implementation of ICollection

        public void Add(T item)
        {
            sessionFactory.GetCurrentSession().Save(item);
        }

        public void Clear()
        {
            throw new NotSupportedException();
        }

        public bool Contains(T item)
        {
            return sessionFactory.GetCurrentSession().Linq<T>().Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            throw new NotSupportedException();
        }

        public int Count
        {
            get
            {
                return sessionFactory.GetCurrentSession().Linq<T>().Count();
            }
        }

        public bool IsReadOnly
        {
            get
            {
                return false;
            }
        }

        public bool Remove(T item)
        {
            sessionFactory.GetCurrentSession().Delete(item);
            return true;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return sessionFactory.GetCurrentSession().Linq<T>().AsEnumerable().GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
        #endregion
    }
}
